
import React from 'react'
import {Link} from 'react-router-dom'
import {Layout,Row,Col,Card,Form, Icon, Input, Button, Checkbox,Spin,Modal,message } from 'antd'

import MMUtile from 'util/mm.jsx'
import User from 'service/user-service.jsx'
import logosm from 'img/logo.jpg'
import userlogin from 'img/userlogin.png'
import FooterMsg from 'component/footermsg/index.jsx'
import PureRenderMixin from 'react-addons-pure-render-mixin'
import Verify from 'component/verify/index.jsx';
import VerifyPhone from 'component/verifyphone/index.jsx';
import Safty from 'service/safty-service.jsx';
const _safty = new Safty();



const { Header, Content, Footer, Sider } = Layout; 
const FormItem = Form.Item;
const _mm = new MMUtile();
const _user = new User();
import './index.css'

class WrappedLogin extends React.Component{
	constructor(props){
    super(props);
    //console.log(this.props.location);
    this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
    this.state={
    	loading:false,
    	username:'',
    	password:'',
    	needCheck:true,
    	visible:false,
    	phone:'',
    	email:'',
    	loginType:'',
    	redirect:_mm.getUrlParam('redirect') || '/',
    	wechatVisible:false
    }
	}
	componentDidMount(){
		if(this.props.location.search =='?p=wechat'){
			this.setState({
				wechatVisible:true
			})
		}
		let username = _mm.getStorage('username')
		if(username && username!="" ){
			this.setState({
				username:_mm.getStorage('username')
			})
		}
	}

  handleLogut(e){
    this.props.history.push('/register')
  }
	handleSubmit(e){
		this.setState({
			loading:true
		})
	  e.preventDefault();
	  this.props.form.validateFields((err, values) => {
	    if (!err) {

				_user.login({
					username:values.username,
					password:values.password
				}).then((res)=>{
		    	this.setState({
						loading:false
					})
					if(res.code==403){
						//打开弹窗
						this.setState({
				      visible: true,
				      phone: res.phone,
				      email:res.email
				    });
						_mm.errorTips('您的账号存在异常，需要通过手机或邮箱的验证码登录');
					}else{
						_mm.setStorage('userInfo',res);
						if(values.remember){
							_mm.setStorage('username',values.username);
						}else{
							_mm.removeStorage('username');
						}
						this.setState({
							needCheck:false
						})
						this.props.history.push(this.state.redirect);							
					}
					
				},(errMsg)=>{

					this.setState({
						loading:false
					})
					_mm.errorTips(errMsg);
				})
	    }else{
	    	this.setState({
					loading:false
				})
	    }
	  });
	}
	getIsCodeRight(callback){
		//获取手机或者邮箱的验证码(登录异常)
		_user.getPhoneOrEmailCode({
			code:callback.code,
			type:callback.phoneOremail
		}).then((res)=>{

			this.setState({
				needCheck:true
			})
			this.props.history.push(this.state.redirect);	
		},(errMsg)=>{
			_mm.errorTips(errMsg)
		})
	}
	getIsCodeRight2(callback){
		//获取手机|验证码(微信登录)
		_safty.codeIsTrue({
			code:callback.code,
			phone:callback.phone
		}).then((res)=>{
			if(_mm.getStorage('loginType')==='QQ'){
				//验证手机号登录
				_safty.beforeLoginBindQQ({
					phone:callback.phone
				}).then((res)=>{
					this.setState({
						wechatVisible:true
					})
					this.props.history.push(this.state.redirect);	
				},(errMsg)=>{
					_mm.errorTips(errMsg)
				})
			}else{
				//验证手机号登录
				_safty.beforeLoginBindWechat({
					phone:callback.phone
				}).then((res)=>{
					this.setState({
						wechatVisible:true
					})
					this.props.history.push(this.state.redirect);	
				},(errMsg)=>{
					_mm.errorTips(errMsg)
				})
			}
			
		},(errMsg)=>{
			_mm.errorTips(errMsg)
		})
	}
	getTypeQQ(){
		_mm.setStorage('loginType','QQ');
		window.location.href="http://sso.rnpig.com/user/qqLogin.act"
	}
	getTypeWechat(){
		_mm.setStorage('loginType','Wechat');
		window.location.href="http://sso.rnpig.com/user/wechatLogin.act"
	}
	handleCancel(e){
    this.setState({
      visible: false,
      wechatVisible: false
    });
  }
	render(){
		const { getFieldDecorator} = this.props.form;
    let winheight =document.body.clientHeight;
    let margintop = (winheight-620)>0?(winheight-620)/2:0;
		return(
			
			<Layout  className="layoutbox">
				<Header  className="headerbox" >
	        <Row >
	          <Col span={24}><img width={300} src={logosm} /></Col>
	        </Row>
	      </Header>	

	      <Layout className="layoutbox">
	      	<Spin spinning={this.state.loading} size="large">
	        <Content className="containerboxlogin" style={{height:winheight-220}}>
	        	<Row style={{marginTop:margintop}}>
	        		<Col span={7}offset={5}><img style={{width:'100%'}} src ={userlogin} /></Col>
							<Col span={6} offset={4}>
								<Card title="登录"  style={{ width: 300,marginTop:'30px' }}>
							    <Form onSubmit={(e)=>{this.handleSubmit(e)}} className="login-form">
						        <FormItem>
						          {getFieldDecorator('username', {
						            rules: [{ required: true, message: '请输入您的用户名!' }],
						            initialValue:this.state.username
						          })(
						            <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="用户名"  />
						          )}
						        </FormItem>
						        <FormItem>
						          {getFieldDecorator('password', {
						            rules: [{ required: true, message: '请输入您的密码!' }],
						            initialValue:this.state.password
						          })(
						            <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="密码" />
						          )}
						        </FormItem>
						        <FormItem>
						          {getFieldDecorator('remember', {
						            valuePropName: 'checked',
						            initialValue: true
						          })(
						            <Checkbox>记住我</Checkbox>
						          )}
						          <div style={{textAlign:'center'}}><Button type="primary" htmlType="submit" className="login-form-button">
						            登录
						          </Button></div>
						          
						          <div style={{textAlign:'center'}}><Link to="/forgetpsw" className="login-form-forgot maincolor" >忘记密码</Link> | <Link to="/accountappeal" className="maincolor">账号申诉</Link> | <a href="javascript:void(0);"   onClick={(e)=>{this.handleLogut(e)}} className="maincolor">马上注册!</a></div>
						          <div style={{textAlign:'center'}}>其他账号登录：<a href="javascript:void:(0)" onClick={this.getTypeQQ.bind(this)} ><Icon type="qq" className="qqiconlittle" /></a> <a href="javascript:void:(0)" onClick={this.getTypeWechat.bind(this)} ><Icon type="wechat" className="wecharticonlittle"  /></a></div>
						        </FormItem>
						      </Form>
							  </Card>
							</Col>
						</Row>
						<Modal
		          title="校验手机"
		          visible={this.state.visible}
        			onCancel={this.handleCancel.bind(this)}
		          footer={null}
		        >
		          <Verify phone={this.state.phone} email={this.state.email} islogin='yes'  getIsCodeRight={this.getIsCodeRight.bind(this)}></Verify>
		        </Modal>	
						<Modal
		          title="登录校验"
		          visible={this.state.wechatVisible}
        			onCancel={this.handleCancel.bind(this)}
		          footer={null}
		        >
		          <VerifyPhone getIsCodeRight2={this.getIsCodeRight2.bind(this)}></VerifyPhone>
		        </Modal>	
	        </Content>
    			</Spin>
	      </Layout>
      	<Footer className="layoutfooter"><FooterMsg /></Footer>
    	</Layout>
		)
	}
}
const Login = Form.create()(WrappedLogin);
export default Login